#include "AT24C02.h"
#include "i2c.h"
#include "BSP.h"

/**
 * 按字节传输数据到AT24C02
 * reg: 内存页数
 * pdata: 传输的数据
 * size: 字节数
 */
void AT24C02_Read(uint8_t reg, uint8_t *pdata, uint16_t size)
{
    HAL_I2C_Mem_Read(&hi2c2, 0xA1, 8 * reg, I2C_MEMADD_SIZE_8BIT, pdata, size, HAL_MAX_DELAY);
}

/**
 * 按字节传输数据到AT24C02
 * reg: 内存页数
 * pdata: 传输的数据
 * size: 字节数
 */
void AT24C02_Write(uint8_t reg, uint8_t *pdata, uint16_t size)
{
    uint8_t count;
    uint8_t leftover;

    count = size / 8;
    leftover = size - count * 8;

    for (uint16_t i = 0; i < size; i++)
    {
        HAL_I2C_Mem_Write(&hi2c2, AT24C02_ADD, 8 * (reg + i), I2C_MEMADD_SIZE_8BIT, pdata + 8 * i, 8, HAL_MAX_DELAY);
        HAL_Delay(5);
    }

    if (leftover == 0)
    {
        return;
    }
    HAL_I2C_Mem_Write(&hi2c2, AT24C02_ADD, reg + 8 * count, I2C_MEMADD_SIZE_8BIT, pdata + 8 * count, 8, HAL_MAX_DELAY);
}

// 擦除
void AT24C02_Erase(uint8_t reg)
{
    HAL_I2C_Mem_Write(&hi2c2, AT24C02_ADD, 8 * reg, I2C_MEMADD_SIZE_8BIT, (uint8_t *)'\0', 8, HAL_MAX_DELAY);
}
